<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('业务系统树')" />
    <th:block th:include="include :: layout-latest-css" />
    <th:block th:include="include :: ztree-css" />
    <th:block th:include="include :: bootstrap-treeview-css" />
    <link th:href="@{/css/common.css}" rel="stylesheet"/>
    <link th:href="@{/css/detail.css}" rel="stylesheet"/>
    <link th:href="@{/css/page_epiboly.css}" rel="stylesheet"/>
    <script th:src="@{/js/go.js}"></script>
</head>
<body class="white-bg business-sys">
<div class="ui-layout-west">
    <div class="box box-main">
        <div class="box box-main">
            <div class="ui-layout-content">
                <div id="tree" class="ztree"></div>
                <input type = "hidden" name = "categoryCode">
                <input type = "hidden" name = "businessId">
            </div>
        </div>
    </div>
</div>

<div class="ui-layout-center">
    <div class="container-div" id="wrapper">
        <!-- Sidebar -->
        <div id="page-content-wrapper">
            <div class="container">
                <div class="pull-left" id = "tableListDiv">
                </div>
                <div class="pull-right">
                    <ul class="nav nav-tabs navtabs nav-table" role="tablist">
                        <li class="active"><a href="#relation-mine" role="tab" data-toggle="tab" data-action = "tableRelation">模型关系（关联我的）</a></li>
                        <li><a href="#mine-relation" role="tab" data-toggle="tab" data-action = "mineRelation">模型关系（我关联的）</a></li>
                        <li><a href="#field-detail" role="tab" data-toggle="tab" data-action="relationFieldList">字段明细</a></li>
                        <li><a href="#model-preview" role="tab" data-toggle="tab" data-action="relationSimpleFieldList">模型预览</a></li>
                    </ul>
                    <div class="tab-content" id="tabContent" style="margin-top: 0px;">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: ztree-js" />
<th:block th:include="include :: bootstrap-treeview-js" />

<script id="tableListTpl" type="text/template">
    <ul class="container-ul">
        {{# layui.each(d, function(index, a){ }}
            <li data-id = "{{a.id}}"><div>{{a.tableName}}</div></li>
        {{# }); }}
    </ul>
</script>
<script id="navContentTpl" type="text/template">
    <div role="tabpanel" class="tab-pane active mt15 relation-mine text-center" id="relation-mine">
        <div id="myDiagramDiv1" style="background-color: white;width: 100%; height: 700px; position: relative; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;">
        <canvas tabindex="0" width="904" height="698" style="position: absolute; top: 0px; left: 0px; z-index: 2; user-select: none; width: 904px; height: 698px; cursor: auto;"></canvas>
        </div>
        </div>
        <div role="tabpanel" class="tab-pane  mt15 mine-relation text-center" id="mine-relation">
        <div id="myDiagramDiv2" style="background-color: white;width: 100%; height: 700px; position: relative; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;">
        <canvas tabindex="0" width="904" height="698" style="position: absolute; top: 0px; left: 0px; z-index: 2; user-select: none; width: 904px; height: 698px; cursor: auto;"></canvas>
        </div>
        </div>
        <div role="tabpanel" class="tab-pane mt15 content-field mlr20" id="field-detail">
        </div>
        <div role="tabpanel" class="tab-pane model-preview mt15 text-center mlr20" id="model-preview">
        </div>
</script>

<script id="contentSimpleFieldTpl" type="text/template">
    <div class="retation-table">
        <ul class="list-group">
            {{# layui.each(d, function(index, a){ }}
            {{# if(a.categorySpace) { }}
            <li class="list-group-item space"></li>
            {{# }}}
            <li class="list-group-item">
                <font style = "width:30px;display: inline-block">{{# if(a.fieldType=='1') { }} PK {{# } else if(a.fieldType == '2') { }} FK {{#} else { }}-{{#}}}</font>
                {{# if(a.fkFieldType=='1') { }}
                <span style="color: red !important;">{{a.fieldName || '一'}}</span>
                <span style="color: red !important;">
						{{a.fieldEnName || '一'}}
					</span>
                {{#} else { }}
                <span>{{a.fieldName || '一'}}</span>
                <span>
						{{a.fieldEnName || '一'}}
					</span>
                {{#}}}
                <span>
						{{a.fieldDataType || '一'}}
						{{# if(a.fieldLength) { }}
								({{a.fieldLength}})
							{{# } }}
					</span>
            </li>
            {{# }); }}
        </ul>
    </div>
</script>

<!--关联字段模板-->
<script id="contentFieldTpl" type="text/template">
    <div class="bootstrap-table bootstrap3">
        <div class="fixed-table-container" style="padding-bottom: 0px;">
            <div class="fixed-table-body">
                <table class="table  table-hover content-field" id="bootstrap-table" style="table-layout:fixed;">
                    <thead>
                    <tr>
                        <th style="width: 80px;">主外键</th>
                        <th style=" width: 200px;">字段中文名称</th>
                        <th style=" width: 200px;">字段名称</th>
                        <th style=" width: 150px;">外键类型</th>
                        <th style=" width: 150px;">字段数据类型</th>
                        <th style=" width: 100px;">字段长度</th>
                        <th style=" width: 100px;">模拟数据</th>
                        <th style=" width: 300px;">模拟数据详细举例</th>
                        <th style=" width: 300px;">字段需求故事</th>
                        <th style=" width: 300px;">是否记录版本</th>
                        <th style=" width: 100px;">是否必填</th>
                        <th style=" width: 100px;">是否作为入参</th>
                        <th style=" width: 100px;">是否风险点</th>
                        <th style=" width: 300px;">风险备注</th>
                        <th style=" width: 80px;"></th>
                    </tr>
                    </thead>
                    <tbody>
                    {{# layui.each(d, function(index, a){ }}
                    <tr>
                        <td style="width: 80px;">{{# if(a.fieldType=='1') { }} PK {{# } else if(a.fieldType == '2') { }} FK {{#} else { }}-{{#}}}</td>
                        {{# if(a.fkFieldType=='1') { }}
                        <td style="color: red;width: 200px;">{{a.fieldName || '一'}}</td>
                        <td style="color: red;width: 200px;">{{a.fieldEnName || '一'}}</td>
                        {{#} else { }}
                        <td style=" width: 200px;">{{a.fieldName || '一'}}</td>
                        <td style=" width: 200px;">{{a.fieldEnName || '一'}}</td>
                        {{#}}}
                        <td style=" width: 150px;">{{# if(a.fkFieldType=='1') { }} 核心模型关系 {{# } else if(a.fkFieldType == '2') { }} 冗余模型关系 {{#} else { }}-{{#}}}</td>
                        <td style=" width: 150px;">{{a.fieldDataType || '--'}}</td>
                        <td style=" width: 100px;">{{a.fieldLength || '--'}}</td>
                        <td style=" width: 100px;">{{a.mockData || '一'}}</td>
                        <td style=" width: 300px;">{{a.mockDescription || '一'}}</td>
                        <td style=" width: 300px;">{{a.fieldStory || '一'}}</td>
                        <td style=" width: 100px;">{{# if(a.isChange=='Y') { }} 是 {{# } else if(a.isChange == 'N') { }} 否 {{#} else { }}-{{#}}}</td>
                        <td style=" width: 100px;">{{# if(a.isRequired=='Y') { }} 是 {{# } else if(a.isRequired == 'N') { }} 否 {{#} else { }}-{{#}}}</td>
                        <td style=" width: 100px;">{{# if(a.isInParam=='Y') { }} 是 {{# } else if(a.isInParam == 'N') { }} 否 {{#} else { }}-{{#}}}</td>
                        <td style=" width: 100px;">{{# if(a.isRisk=='Y') { }} 是 {{# } else if(a.isRisk == 'N') { }} 否 {{#} else { }}-{{#}}}</td>
                        <td style=" width: 300px;">{{a.riskRemark || '一'}}</td>
                        <td style=" width: 80px;">
                            {{# if(a.isFieldEnum=='Y') { }}
                            <a onclick="queryFieldEnum({{a.dictId}})">查看枚举</a>
                            {{#}}}
                            {{# if(a.fieldType=='2') { }}
                            <a onclick="queryFKRelation({{a.id}})">查看外键</a>
                            {{#}}}
                        </td>
                    </tr>
                    {{# }); }}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</script>
<script id="boxMainTabsTpl" type="text/template">
    <div role="tabpanel" class="tab-pane active mt15 box-swiper-li" id="{{d.id}}">
        {{# if(d.id=='box-dubbo'){ }}
        <select class="form-control state-select">
            <option value="1" selected="selected">不限版本</option>
            <option value="2">张三 前端工程师</option>
            <option value="3">李四 业务架构师</option>
        </select>
        {{# } }}
        <ul>
            {{# layui.each(d.data, function(index, a){ }}
            <li data-id="{{a.userId}}" data-type="{{d.type}}"
                class="{{# if(index == 0){ }}active{{# } else { }}{{# }}}">
                <div>
                    <p><span>{{a.username}}</span>
                        <font class="pull-right">{{d.name}}：{{a.dataFinishCount}}/{{a.dataTotalCount}}</font>
                    </p>
                    <p style="display: flex;align-items: center;"><span style="width: 118px;">{{a.roleName}}</span><span>{{# if(a.status == 0){ }}未完成{{# } else if(a.status == 1){ }}进行中{{# } else { }}已完成{{# }}}<span></p>
                </div>
            </li>
            {{# }); }}
        </ul>
    </div>
</script>

<script>
    var prefix = ctx + "businessSystem/businessSystem/new", pageData;
    $(function() {
        $('body').layout({ initClosed: false, west__size: 200 });
        $(".content-table li").click(function(){
            $(".content-table li").removeClass("active")
            $(this).addClass("active")
        })
        $(".tab-content li").click(function(){
            $("#wrapper").removeClass("toggled").addClass("all-toggled")
        });
        // 加载分类树
        queryCategoryTree();
        tableList();
    });

    $("body").on('click','.container-ul li',function(){
        $(".container-ul li").removeClass("active")
        $(this).addClass("active");
        pageData.id = $(this).data("id");
        window.myDiagram1 = null;
        window.myDiagram2 = null;
        var navContentTplHtml = $("#navContentTpl").html();
        laytpl(navContentTplHtml).render({}, function (html) {
            $("#tabContent").empty();
            $("#tabContent").html(html);
        });
        $(".nav-table li:eq(0) a").click()
    }).on('click','.nav-table a',function(){
        window[$(this).data("action")]();
    });

    /**
     * 分类树
     */
    function queryCategoryTree() {
        var url = ctx + "category/category/treeDataForContainsObject?type=1";
        var options = {
            url: url,
            expandLevel: 2,
            onClick : zOnClick
        };
        $.tree.init(options);
        function zOnClick(event, treeId, treeNode) {
            $("#deptId").val(treeNode.id);
            $("#parentId").val(treeNode.pId);
            $.table.search();
            $("input[name='categoryCode']").val(treeNode.code);
            var attribute = treeNode.attribute;
            // 标识节点为业务系统
            if (attribute != null && attribute.type == 2) {
                $("input[name='businessId']").val(treeNode.id);
            }
            tableList();
        }
    }

    /**
     * 页面页表
     * @param params
     */
    function tableList() {
        let params = {};
        params.categoryCode = $("input[name='categoryCode']").val();
        params.businessId = $("input[name='businessId']").val();
        let config = {
            url: prefix + "/tableList",
            type: "post",
            dataType: "json",
            data: params,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    let data = result.data || [];
                    pageData = data[0];
                    var tableListTplHtml = $("#tableListTpl").html();
                    laytpl(tableListTplHtml).render(data, function (html) {
                        $("#tableListDiv").empty();
                        $("#tableListDiv").append(html);
                    });
                    $('.container-ul li:eq(0)').click();
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                    return false;
                }
                $.modal.alertError(result.msg);
            }
        };
        $.ajax(config);
    }

    /**
     * 模型预览
     * @param pageData
     * @returns {boolean}
     */
    function relationSimpleFieldList() {
        var params = {};
        params.tableId = pageData.id;
        var resultJson;
        var config = {
            url: ctx + "table/table/fieldInfoList",
            type: "POST",
            dataType: "json",
            async: false,
            data: params,
            success: function (result) {
                if (result && result.code == 0) {
                    resultJson = result.data;
                }
            }
        };
        $.ajax(config);
        if(!resultJson) {
            return false;
        }
        let category = resultJson[0].category;
        $.each(resultJson, function (indexB, a) {
            a.categorySpace = false;
            if (category != a.category) {
                a.categorySpace = true;
                category = a.category;
            }
        });
        var contentSimpleFieldTplHtml = $("#contentSimpleFieldTpl").html();
        laytpl(contentSimpleFieldTplHtml).render(resultJson, function (html) {
            $("#model-preview").empty();
            $("#model-preview").html(html);
        });
    };

    /**
     * 字段明细
     * @param pageData
     * @returns {boolean}
     */
    function relationFieldList() {
        var params = {};
        params.tableId = pageData.id;
        var resultJson;
        var config = {
            url: ctx + "table/table/fieldInfoList",
            type: "POST",
            dataType: "json",
            async: false,
            data: params,
            success: function (result) {
                if (result && result.code == 0) {
                    resultJson = result.data;
                }
            }
        };
        $.ajax(config)
        if(!resultJson) {
            return false;
        }
        var contentFieldTplHtml = $("#contentFieldTpl").html();
        laytpl(contentFieldTplHtml).render(resultJson, function (html) {
            $("#field-detail").empty();
            $("#field-detail").html(html);
        });
    };

    /**
     * 关联关系  默认关联我的
     * @param pageData
     * @param id id名称
     * @param path 接口路径
     * @returns {boolean}
     */
    function tableRelation(id="1",path="/tableRef") {
        if (window.goSamples) goSamples();
        if (window['myDiagram'+id]){
            return false;
        }
        var $go = go.GraphObject.make;
        window['myDiagram'+id] =
            $go(go.Diagram, `myDiagramDiv`+id,
                {
                    allowDelete: false,
                    allowCopy: false,
                    layout: $go(go.ForceDirectedLayout),
                    "undoManager.isEnabled": true
                });
        // name设置
        console.log(window['myDiagram'+id])
        var itemTempl =
            $go(go.Panel, "Horizontal",
                $go(go.Panel, "Table",
                    $go(go.RowColumnDefinition,{ row: 1, separatorStrokeWidth: 1.5, separatorStroke: "black" }),
                    $go(go.TextBlock, new go.Binding("text", "keyType"), { row: 1, column: 0, width:18, margin: new go.Margin(2, 4, 2, 0) }),
                    $go(go.TextBlock, new go.Binding("text", "keyName"), { row: 1, column: 1, width:140, margin: new go.Margin(2, 10, 2, 4) }),
                    $go(go.TextBlock, new go.Binding("text", "keyEnName"), { row: 1, column: 2, width:160, margin: new go.Margin(2, 10, 2, 4) }),
                    $go(go.TextBlock, new go.Binding("text", "dataType"), { row: 1, column: 3, margin: new go.Margin(2, 10, 2, 4) }),
                    $go(go.TextBlock, new go.Binding("text", "remark"), { row: 1, column: 4, margin: new go.Margin(2, 10, 2, 4) }),
                )
            );
        // 节点模板
        window['myDiagram'+id].nodeTemplate =
            $go(go.Node, "Auto",
                {
                    selectionAdorned: true,
                    resizable: true,
                    layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized,
                    fromSpot: go.Spot.AllSides,
                    toSpot: go.Spot.AllSides,
                },
                new go.Binding("location", "location").makeTwoWay(),
                new go.Binding("desiredSize", "visible", function(v) {
                    return new go.Size(NaN, NaN);
                }).ofObject("LIST"),
                $go(go.Shape, "RoundedRectangle", {
                    fill: 'white',
                    stroke: "#000",
                    strokeWidth: 1
                }),
                $go(go.Panel, "Table", {
                        defaultRowSeparatorStroke: "black",
                    },
                    // 表格头部表明名称
                    $go(go.TextBlock, {
                            row: 0,
                            alignment: go.Spot.Center,
                            margin: new go.Margin(5, 24, 5, 24),
                            font: "bold 14px sans-serif"
                        },
                        new go.Binding("text", "key")
                    ),
                    $go(go.Panel, "Vertical", {
                            name: "LIST",
                            row: 1,
                            padding: 3,
                            alignment: go.Spot.TopLeft,
                            defaultAlignment: go.Spot.Left,
                            stretch: go.GraphObject.Horizontal,
                            itemTemplate: itemTempl
                        },
                        new go.Binding("itemArray", "items")),
                )
            );
        window['myDiagram'+id].linkTemplate =
            $go(go.Link,
                {
                    selectionAdorned: true,
                    layerName: "Foreground",
                    reshapable: true,
                    routing: go.Link.AvoidsNodes,
                    corner: 5,
                    curve: go.Link.JumpOver
                },
                $go(go.Shape,
                    { strokeWidth: 2, stroke: '#303B45' }),
                $go(go.Shape,
                    { toArrow: "Standard", fill: '#303B45', stroke: null })
            );
        var params = {};
        params.tableId = pageData.id;
        var resultJson;
        var config = {
            url: ctx + "table/table" + path,
            type: "POST",
            dataType: "json",
            async: false,
            data: params,
            success: function (result) {
                resultJson = result;
            }
        };
        $.ajax(config);
        // 表格内部数据
        var nodeDataArray = resultJson.nodeDataArray;
        //数据块关联关系
        var linkDataArray = resultJson.linkDataArray;;
        window['myDiagram'+id].model = $go(go.GraphLinksModel, {
            copiesArrays: true,
            copiesArrayObjects: true,
            nodeDataArray: nodeDataArray,
            linkDataArray: linkDataArray
        });
    }

    /**
     * 模型关系我关联
     */
    function mineRelation(){
        tableRelation('2','/tableRef2')
    }
</script>
</body>
</html>
